package com.zzzzzz.core.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zzzzzz.common.util.Validator;
import com.zzzzzz.core.dao.ClassNameDao;
import com.zzzzzz.core.exception.SystemException;
import com.zzzzzz.core.exception.ZzzzzzException;
import com.zzzzzz.core.model.po.ClassName;

@Service
public class ClassNameManager {

	@Resource
	private ClassNameDao classNameDao;
	
	public ClassName addClassName(String value) throws SystemException {
		ClassName className = new ClassName();
		className.setValue(value);
		classNameDao.add(className);
		return className;
	}
	
	public ClassName getClassName(long classNameId) throws ZzzzzzException, SystemException {
		return classNameDao.findById(classNameId);
	}
	
	public ClassName getClassName(String value) throws SystemException {
		if (Validator.isNull(value)) {
			return _nullClassName;
		}

		// Always cache the class name. This table exists to improve
		// performance. Create the class name if one does not exist.

		ClassName className = _classNames.get(value);

		if (className == null) {
			className = classNameDao.findByValue(value);

			if (className == null) {
				className = addClassName(value);
			}

			_classNames.put(value, className);
		}

		return className;
	}
	
	public long getClassNameId(String value) throws SystemException {
		ClassName className = getClassName(value);
		return className.getClassNameId();
	}
	
	private static ClassName _nullClassName = new ClassName();
	
	private static Map<String, ClassName> _classNames = new ConcurrentHashMap<String, ClassName>();

}
